package com.sinodata.bsm.cicp.finder.aix;

/**
 * AIX交换分区发现程序.
 * 程序返回：交换分区大小
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

public class Swap extends AixFinder {
    private static final Logger logger = Logger.getLogger(Swap.class);
    private static final String SHELL = "lsps -s";

    /**
     * 使用命令lsps -s
     * Total Paging Space   Percent Used
     *       4096MB              44%
     * 4096MB即为swap的大小
     */

    public static void main(String[] args) {

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] swapRes = null;
        BufferedReader reader = null;
        String strLine = null;
        String regex = "\\s+(\\d+)MB\\s+.*";
        Pattern pattern = Pattern.compile(regex);
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    swapRes = new String[4];
                    list.add(swapRes);
                    swapRes[0] = "0"; //资源唯一标示
                    swapRes[1] = "SWAP 0"; //资源名称
                    swapRes[2] = getHostName(ip) + "SWAP"; //资源描述
                    swapRes[3] = matcher.group(1);//交换分区大小
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to find aix swap", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }
}
